<!--
 * @Author: zhangjingyu
 * @Date: 2021-04-01 09:30:30
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-05-19 09:21:55
 * @FilePath: \vprisk10.14\src\views\ftpManage\pricingManage\sceneTask\sceneTask_dataFilter.vue
 * @Description: 数据筛选页面
-->
<template>
  <div>
    <div style="display:flex;min-height:80vh;">
      <div style="flex:35%;border-right:1px solid #ccc">
        <span class="formTitle"><i class="vertical-bar"></i>数据筛选</span>
        <el-form
          :model="searchForm"
          ref="filterForm"
          label-width="120px"
          label-position="right"
          size="mini"
          :rules="searchRules"
        >
          <el-form-item label="情景分析编号：" prop="taskCode">
            <el-input
              v-model="searchForm.taskCode"
              style="width: 200px"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="头寸数据表：" prop="position">
            <el-select
              v-model="searchForm.position"
              :multiple="true"
              @change="$forceUpdate()"
              style="display:inline-block;width: 150px"
            >
              <el-option
                v-for="item in positionList"
                :key="item.pdPostFix"
                :label="item.pdName"
                :value="item.pdPostFix"
              ></el-option>
            </el-select>
            <el-button
              @click="positionCheck"
              style="display:inline-block;min-width:50px;"
              >选择</el-button
            >
          </el-form-item>
          <el-form-item label="添加过滤条件：" prop="businessEle">
            <el-select
              v-model="searchForm.businessEle"
              filterable
              style="width: 200px"
            >
              <el-option-group label="　　　元素字段　　　　　　　　元素名称">
                <!-- <el-option
                    v-for="item in businessEleList"
                    :key="item.pdPostFix"
                    :label="
                      item.elementField + ' --------- ' + item.elementName
                    "
                    :value="item.elementField"
                    @click.native="checkCusinessEle(item)"
                  ></el-option> -->
                <el-option
                  v-for="item in businessEleList"
                  :key="item.pdPostFix"
                  :label="item.elementName"
                  :value="item.elementField"
                  @click.native="checkCusinessEle(item)"
                >
                  <tr style="border-bottom:1px solid #ccc;text-align:center">
                    <td style="width:150px;">{{ item.elementField }}</td>
                    <td style="width:150px;">{{ item.elementName }}</td>
                  </tr>
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
        </el-form>
        <!-- 字段循环体 -->
        <filter-form-item
          v-for="item in conditionItemList"
          :key="item.elementField"
          :itemObj="item"
        ></filter-form-item>
        <div>
          <el-button @click="fliterFunc">数据筛选</el-button>
          <el-button @click="toFilterData">查看筛选数据</el-button>
          <el-button @click="backpage">返回</el-button>
        </div>
        <!-- 头寸表选择弹窗 -->
        <position-table
          :positionShow.sync="positionShow"
          @check="checkPosition"
        ></position-table>
      </div>
      <div style="flex:65%;padding-left:20px">
        <span class="formTitle"><i class="vertical-bar"></i>历史筛选条件</span>
        <div id="hisSifData">
          <el-button @click="hisToFliterData">应用</el-button>
          <el-button @click="delHisSifData">删除</el-button>
        </div>
        <el-table :data="hisTableData" ref="hisTable" @row-click="rowChecked">
          <el-table-column width="55" type="selection"></el-table-column>
          <el-table-column
            prop="pdName"
            label="头寸数据表"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="condition"
            label="过滤条件"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column prop="siftTm" label="过滤时间" show-overflow-tooltip>
          </el-table-column>
        </el-table>
        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="hisForm.page"
          :page-size="hisForm.size"
          @refresh="queryHisTableDt"
          :total="hisTotal"
        ></pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { pricingTask } from "@/api/index";
import positionTable from "./positionTable";
import filterFormItem from "./filterFormItem";
export default {
  components: { positionTable, filterFormItem },
  data() {
    return {
      positionShow: false,

      searchForm: {
        taskCode: this.code,
        businessEle: "",
        position: []
      },
      hisForm: {
        taskCode: this.code,
        page: 1,
        size: 15
      },
      hisTotal: 100,
      searchRules: {
        position: [
          {
            required: true,
            message: "必须选择头寸表",
            trigger: ["bulr", "change"]
          }
        ]
      },
      // 头寸下拉
      positionList: [],
      // 过滤字段下拉
      businessEleList: [],
      // 过滤条件集合
      conditionItemList: [],
      // 历史筛选数据表
      hisTableData: []
    };
  },
  props: {
    code: {
      type: String,
      default: ""
    }
  },
  watch: {
    code(n, o) {
      this.searchForm.taskCode = n;
      this.initFilter();
      this.queryHisTableDt();
    }
  },
  created() {
    this.queryListForCombogrid();
    this.queryHisTableDt();
  },
  mounted() {},
  methods: {
    initFilter() {
      this.searchForm.businessEle = "";
      this.searchForm.position = [];
      this.positionList = [];
      this.conditionItemList = [];
    },
    toFilterData() {
      let ary = [],position = this.searchForm.position,positionList=this.positionList
      for (let i = 0; i < position.length; i++) {
        for (let j = 0; j < positionList.length; j++) {
          if(position[i]==positionList[j].pdPostFix){
            ary .push(positionList[j])
          }
        }
      }
      console.log(ary)
      this.$emit("toFilterData", ary);
    },
    backpage() {
      this.$emit("backIndex", false);
    },
    // 分页查询历史筛选数据
    queryHisTableDt() {
      let data = this.hisForm;
      pricingTask.sceneTaskConditionFindHistory(data).then(res => {
        if (res.code == 200) {
          this.hisTableData = res.rows;
          this.hisTotal = res.total;
        }
      });
    },
    positionCheck() {
      this.positionShow = true;
    },
    // 行点击
    rowChecked(row) {
      if (this.$refs.hisTable) {
        this.$refs.hisTable.clearSelection();
        this.$refs.hisTable.toggleRowSelection(row, true);
      }
    },
    // 获取筛选数据下拉数据
    queryListForCombogrid() {
       pricingTask.queryListForCombogrid().then(res => {
        if (res.code == 200) {
          this.businessEleList = res.datas.filter(v => {
            return !v.elementField.endsWith("Mult")&&!v.elementField.startsWith('append');
          }).concat(res.datas.filter(v => {
            return v.elementField.startsWith('append');
          }));
        }
      });
    },
    checkPosition(val) {
      console.log(val);
      //   头寸表选中数据，添加到选择框中，下拉框去重
      if (this.positionList.length == 0) {
        this.positionList = [...val];
      } else {
        for (let i = 0; i < val.length; i++) {
          if (
            this.positionList.findIndex(
              item => item.pdPostFix == val[i].pdPostFix
            ) == -1
          ) {
            this.positionList.push(val[i]);
          }
        }
      }
      this.searchForm.position = val.map(v => v.pdPostFix);
      this.positionShow = false;
      this.$forceUpdate();
    },
    checkCusinessEle(obj) {
      console.log(obj);
      // 去重添加
      let isrepeat = false;
      this.conditionItemList.forEach(item => {
        if (item.elementField == obj.elementField) {
          isrepeat = true;
        }
      });
      // 识别类型，初始化相应v值
      if (isrepeat) return;
      let o = { ...obj };
      o.checked = true;
      o.op = "=";
      o.v = "";
      if (o.elementType === "2") {
        o.vn = "";
      }
      if (o.elementType === "4") {
        o.v = [];
      }
      if (o.elementType === "5") {
        o.vMult = "";
      }
      this.conditionItemList.push(o);
    },
    // 校验每一项
    validFilterItems() {
      let list = this.conditionItemList.filter(item => item.checked === true);
      let warningstr = "";
      for (let i = 0; i < list.length; i++) {
        if (list[i].v == "") {
          warningstr = "有选项未输入值，请检查";
          break;
        }
        if (
          list[i].op == "><" &&
          list[i].elementType == "2" &&
          list[i].vn == ""
        ) {
          warningstr = "有选项未输入值，请检查";
          break;
        }
        if (list[i].elementType == "5" && list[i].vMult == "") {
          warningstr = "有选项未输入值，请检查";
          break;
        }
      }
      return warningstr;
    },
    // 数据筛选-> table
    fliterFunc() {
      let arr = this.conditionItemList.filter(item => item.checked === true);
      console.log(arr);
      this.$refs["filterForm"].validate(valid => {
        if (valid) {
          // 校验每一项
          let str = this.validFilterItems();
          if (str != "") return this.$message.warning(str);
          let data = {
            taskCode: this.searchForm.taskCode,
            position: this.searchForm.position.toString(),
            f: arr.map(v => v.elementField)
          };
          arr.forEach(item => {
            this.$set(data, `op[${item.elementField}]`, item.op);
            let v_arr = [];
            // 判断字符串类型
            if (typeof item.v === "string") {
              //    数字类型介于
              if (item.elementType === "2" && item.op === "><") {
                v_arr.push(item.v);
                v_arr.push(item.vn);
              }
              // 期限类型
              else if (item.elementType === "5") {
                v_arr.push(item.v + item.vMult);
              }
              // 单个字符串text、单个nubler或单个日期
              else {
                v_arr.push(item.v);
              }
            }
            // 不是字符串类型就是数组 直接赋值
            else {
              v_arr = [...item.v];
            }

            this.$set(data, `v[${item.elementField}]`, v_arr);
          });
          // 全部处理成字符串逗号分割
          for (let k in data) {
            data[k] = data[k].toString();
          }
          // 请求数据筛选接口
          pricingTask.sceneTaskSiftData(data).then(res => {
            if (res.code == 200) {
              console.log(res);
              this.queryHisTableDt();
            }
          });
        }
      });
    },

    // 应用数据 table ->筛选项
    hisToFliterData() {
      let selection = this.$refs.hisTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行应用");
      }
      let row = selection[0];
      // 应用头寸表选中项
      let codeList = row.pdPostfix.split(",");
      let nameList = row.pdName.split(",");
      let positionList = [];
      for (let i = 0; i < codeList.length; i++) {
        let obj = { pdPostFix: codeList[i], pdName: nameList[i] };
        positionList.push(obj);
      }
      this.positionList = positionList;
      this.searchForm.position = codeList;
      this.searchForm.businessEle = "";
      // 应用过滤条件item集合
      let itemList = [];
      for (let i = 0; i < row.siftConditions.length; i++) {
        let index = this.businessEleList.findIndex(
          v => v.elementField === row.siftConditions[i].elementField
        );
        if (index != -1) {
          let obj = { ...this.businessEleList[index] },
            rowItem = row.siftConditions[i];
          // 识别类型，初始化相应op值和v值
          obj.checked = true;
          obj.op = rowItem.condition;
          obj.v = rowItem.conditionValue;
          //数字类型
          if (obj.elementType === "2") {
            obj.vn = "";
            // 如果是介于
            if (rowItem.condition === "><") {
              obj.v = rowItem.conditionValue.split(",")[0] || "";
              obj.vn = rowItem.conditionValue.split(",")[1] || "";
            }
          }
          // 日期类型
          if (obj.elementType === "3") {
            // 如果是介于
            if (rowItem.condition === "><") {
              let val = rowItem.conditionValue.split(",");
              val.length = 2;
              obj.v = val;
            } else {
              obj.v = rowItem.conditionValue;
            }
          }
          // 值为数组类型：字典 维度 口径 币种
          if (
            obj.elementType === "4" ||
            obj.elementType === "6" ||
            obj.elementType === "7" ||
            obj.elementField === "cpm_dim_currency"
          ) {
            let val = rowItem.conditionValue.split(",");
            // 去除最后的逗号造成的空项
            if (val[val.length - 1] == "") {
              val.length = val.length - 1;
            }
            obj.v = val;
          }
          // 期限类型
          if (obj.elementType === "5") {
            let termstr = rowItem.conditionValue.split("");
            obj.vMult = termstr[termstr.length - 1];
            termstr.length = termstr.length - 1;
            obj.v = termstr.join("");
          }
          itemList.push(obj);
        }
      }
      this.conditionItemList = itemList;
      console.log(itemList);
      this.$forceUpdate();
    },
    // 删除历史筛选数据
    delHisSifData() {
      let selection = this.$refs.hisTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请至少选择一条数据进行删除");
      }
      let data = selection.map(v => v.siftConditionNum);
      pricingTask.sceneTaskConditionRemove(data).then(res => {
        if (res.code == 200) {
          this.$message.success("删除成功");
          this.queryHisTableDt();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    handleSizeChange(val) {
      this.hisForm.size = val;
      this.queryHisTableDt();
    },
    handleCurrentChange(val) {
      this.hisForm.page = val;
      this.queryHisTableDt();
    }
  }
};
</script>

<style lang="scss" scoped>
.formTitle {
  font-size: 14px;
  font-weight: 700;
  display: block;
  margin-bottom: 10px;
}
#hisSifData {
  height: 50px;
}
</style>